


require"misc"
require"protoairdef"
require"linkout"
require"linkin"
module(...,package.seeall)

local ready = false

function isReady() return ready end

-- local function enPwd(s)
-- 	local tmp,ret,i = 0,""
-- 	for i=1,string.len(s) do
-- 		tmp = bit.bxor(tmp,string.byte(s,i))
-- 		if i % 3 == 0 then
-- 			ret = ret..string.char(tmp)
-- 			tmp = 0
-- 		end
-- 	end
-- 	return string.toHex(ret)
-- end

local co_monitor = sys.taskInit(function()
	sys.waitUntil('IMSI_READY')
	if sim.getStatus() then
		while true do
			if sys.wait(1800000) == nil then
				sys.restart('monitor timeout')
			end
		end
	end
end)

sys.taskInit(
	function()
		while true do
			while not socket.isReady() do sys.waitUntil('IP_READY_IND') end
			local imei = misc.getImei()

			log.error("--zbb--linkair.taskInit net ok!!!!")
			--创建一个socket tcp客户端
			local socketClient = socket.tcp()
			--阻塞执行socket connect动作，直至成功
			local servAddr = nvm.get("addr")
			local servPort = nvm.get("port")
			local servProt = nvm.get("prot")
			log.info("--zbb--servAddr port:->",servAddr,servPort,servProt)
			while not socketClient:connect(servAddr,servPort) do
				sys.wait(2000)
			end
			ready = true

			linkout.init()
			while true do
				if not linkin.procMsg(socketClient) then log.error("--zbb--linkair linkin.procMsg error") break end
				if not linkout.procMsg(socketClient) then log.error("--zbb--linkair linkout.procMsg error") break end
				coroutine.resume(co_monitor, 'feed monitor')
			end
			linkout.unInit()
			log.error("--zbb--linkair.taskInit net error!!!!")

			ready = false
			--断开socket连接
			socketClient:close()
		end
	end
)
